package com.hnit.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnit.mapper.AddressMapper;
import com.hnit.web.Clients.IdServiceClient;
import com.hnit.web.DTO.AddressDTO;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hnit.web.Utils.ResponseResult;
import com.hnit.web.bean.Address;
import com.hnit.service.AddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

/**
 * @program: shopping147_cloud
 * @description: 用户地址服务实现
 * @author: zy
 * @create: 2025-08-03 15:20
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private IdServiceClient idServiceClient;

    @Override
    public List<AddressDTO> getAddressesByUserId(Long userId) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, userId)
                .eq(Address::getAddressStatus, 1);
        List<Address> addresses = addressMapper.selectList(queryWrapper);
        return addresses.stream().map(address -> {
            AddressDTO dto = new AddressDTO();
            BeanUtils.copyProperties(address, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public AddressDTO addAddress(AddressDTO addressDTO) {
        // 生成地址ID
        ResponseResult rr = idServiceClient.getNextId();
        if (rr.getCode() != 1) {
            throw new RuntimeException("地址ID生成失败");
        }
        Long addressId = Long.parseLong(rr.getData().toString());
        addressDTO.setAddressId(addressId);

        // 设置默认状态
        if (addressDTO.getAddressStatus() == null) {
            addressDTO.setAddressStatus(1); // 默认正常
        }

        // 检查用户是否已有其他地址
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, addressDTO.getUserId())
                .eq(Address::getAddressStatus, 1);
        long addressCount = addressMapper.selectCount(queryWrapper);
        // 如果是用户第一个地址，设置为默认地址
        if (addressCount == 0) {
            addressDTO.setIsDefault(1);
        } else if (addressDTO.getIsDefault() == null) {
            addressDTO.setIsDefault(0); // 默认非默认地址
        }

        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);
        // 如果设置为默认地址，取消其他默认地址
        if (address.getIsDefault() == 1) {
            addressMapper.cancelDefaultByUserId(address.getUserId());
        }
        int result = addressMapper.insert(address);
        if (result > 0) {
            BeanUtils.copyProperties(address, addressDTO);
            return addressDTO;
        } else {
            throw new RuntimeException("地址添加失败");
        }
    }

    @Override
    @Transactional
    public AddressDTO updateAddress(AddressDTO addressDTO) {
        if (addressDTO.getAddressId() == null) {
            throw new IllegalArgumentException("地址ID不能为空，无法更新");
        }
        Address address = addressMapper.selectById(addressDTO.getAddressId());
        if (address == null) {
            throw new RuntimeException("地址不存在，地址ID: " + addressDTO.getAddressId());
        }
        BeanUtils.copyProperties(addressDTO, address);
        // 如果设置为默认地址，取消其他默认地址
        if (address.getIsDefault() == 1) {
            addressMapper.cancelDefaultByUserId(address.getUserId());
        }
        int result = addressMapper.updateById(address);
        if (result > 0) {
            return getAddressById(addressDTO.getAddressId());
        } else {
            throw new RuntimeException("地址更新失败，地址ID: " + addressDTO.getAddressId());
        }
    }

    @Override
    @Transactional
    public boolean deleteAddress(Long addressId) {
        Address address = addressMapper.selectById(addressId);
        if (address == null) {
            return false;
        }
        // 检查是否是用户最后一个地址
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, address.getUserId())
                .eq(Address::getAddressStatus, 1);
        long addressCount = addressMapper.selectCount(queryWrapper);
        if (addressCount <= 1) {
            throw new RuntimeException("无法删除用户最后一个地址，地址ID: " + addressId);
        }
        address.setAddressStatus(0);
        int result = addressMapper.updateById(address);
        return result > 0;
    }

    @Override
    public AddressDTO getAddressById(Long addressId) {
        Address address = addressMapper.selectById(addressId);
        if (address == null) {
            return null;
        }
        AddressDTO dto = new AddressDTO();
        BeanUtils.copyProperties(address, dto);
        return dto;
    }

    @Override
    @Transactional
    public boolean setDefaultAddress(Long addressId, Long userId) {
        Address address = addressMapper.selectById(addressId);
        if (address == null || !address.getUserId().equals(userId)) {
            return false;
        }
        addressMapper.cancelDefaultByUserId(userId);
        address.setIsDefault(1);
        int result = addressMapper.updateById(address);
        return result > 0;
    }
}